import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Request,
  Put,
  Query,
} from "@nestjs/common";
import { Public } from "src/utils/decorators/public.decorator";
import { CreateUserDto } from "./dto/create-user.dto";
import { UserService } from "./user.service";
import { Roles } from "src/utils/decorators/roles.guard";
import { UpdateUserDto } from "./dto/update-user.dto";
import { JwtPayload } from "src/utils/interfaces/jwt.interface";
import { ApiBearerAuth, ApiOperation, ApiTags } from "@nestjs/swagger";

@Controller("user")
@ApiTags("用户")
@ApiBearerAuth()
export class UserController {
  constructor(private readonly usersService: UserService) {}

  @Public()
  @ApiOperation({ summary: "测试, 无任何作用" })
  @Get("test")
  test(@Query() query) {
    console.log("Received request", query);
    return null;
  }

  @Get("list")
  @ApiOperation({
    summary: "如果是管理员, 查看所有用户; 如果不是, 则查看本公司所有用户 ",
  })
  list(@Request() req) {
    if (req.user.aud === "admin") {
      return this.usersService.findAll();
    } else {
      const companyId = req.user.company;
      return this.usersService.findByCompany(companyId);
    }
  }

  @Public()
  @ApiOperation({
    summary:
      "创建新的管理员, 这一行为应当隐藏起来, 第一次使用项目时使用这个接口, 后续应当关闭这个接口",
  })
  @Post("hidden")
  createAdmin(@Body() createUserDto: CreateUserDto) {
    createUserDto.role = "admin";
    return this.usersService.create(createUserDto);
  }

  @Public()
  @Post()
  @Roles("manager")
  @ApiOperation({
    summary: "为登录用户所在公司创建新用户, 经理有此权限",
  })
  create(
    @Body() createUserDto: CreateUserDto,
    @Request() req: { user: JwtPayload }
  ) {
    const companyId = req.user.company;
    return this.usersService.create(createUserDto, companyId);
  }

  @ApiOperation({
    summary: "获取当前登录用户的用户信息",
  })
  @Get("profile")
  getProfile(@Request() req: { user: JwtPayload }) {
    if (req.user) {
      return this.usersService.find(req.user.sub);
    }
  }

  @Put()
  @ApiOperation({
    summary: "更新当前登录用户的信息",
  })
  updateAuth(@Body() updateUserDto: UpdateUserDto, @Request() req) {
    return this.usersService.update(req.user.sub, updateUserDto);
  }

  @ApiOperation({
    summary: "查找某一个公司的所有用户，只有管理员有权限",
  })
  @Get("list/:companyId")
  @Roles("admin")
  listByCompany(@Param("companyId") companyId: string) {
    return this.usersService.findByCompany(companyId);
  }

  @Get(":id")
  @ApiOperation({
    summary: "通过ID查找某一个用户",
  })
  findById(@Param("id") id: string) {
    return this.usersService.find(id);
  }

  @ApiOperation({
    summary: "更新某一个用户的信息, 只有经理或管理者有此权限",
  })
  @Put(":id")
  @Roles("manager", "admin")
  update(@Param("id") id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.usersService.update(id, updateUserDto);
  }

  @ApiOperation({
    summary: "删除某一个用户, 只有经理或管理者有此权限",
  })
  @Delete(":id")
  @Roles("manager", "admin")
  delete(@Param("id") id: string) {
    return this.usersService.remove(id);
  }
}
